package com.zyy.smartcity1129.movecar;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.zyy.smartcity1129.data.MoveCarInfo;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: MoveCarDataAdapter$
 * @Description: 作用
 * @Author: letquit
 * @CreateDate: 12/11/2021$
 * @Version: 1.0
 */
public class MoveCarDataAdapter {
    private MoveCarMySQLiteOpenHelper openHelper;
    private SQLiteDatabase database;

    public void openDB(Context context){
        openHelper = new MoveCarMySQLiteOpenHelper(context, "MoveCar1.db", null, 1);
        try{
            database = openHelper.getWritableDatabase();
        } catch (Exception e) {
            database = openHelper.getReadableDatabase();
        }
    }

    public void closeDB() {
        if (database != null) {
            database.close();
            database = null;
        }
        if (openHelper != null) {
            openHelper.close();
            openHelper = null;
        }
    }

    public List<MoveCarInfo> QueryAll(Context context) {
        List<MoveCarInfo> cartList = new ArrayList<>();
        openDB(context);
        Cursor cursor = database.query("MoveCar", null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                int id = cursor.getInt(0);
                String carnum = cursor.getString(1);
                String phone = cursor.getString(2);
                String address = cursor.getString(3);
                cartList.add(new MoveCarInfo(carnum, phone, address));
            } while (cursor.moveToNext());
        }
        cursor.close();
        closeDB();
        return cartList;
    }

    public long insert(Context context, MoveCarInfo moveCarInfo) {
        openDB(context);
        ContentValues values = new ContentValues();
        values.put("carnum", moveCarInfo.getCarnum());
        values.put("phone", moveCarInfo.getPhone());
        values.put("address", moveCarInfo.getAddress());
        long result = database.insert("MoveCar", null, values);
        closeDB();
        return result;
    }
}
